<template>
    <el-form :model="form" :rules="rules" ref="form" label-width="100px">
      <el-form-item label="旧密码" prop="oldPassword">
        <el-input type="password" v-model="form.oldPassword"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="password">
        <el-input type="password" v-model="form.password"></el-input>
      </el-form-item>
      <el-form-item label="确认新密码" prop="confirmPassword">
        <el-input type="password" v-model="form.confirmPassword"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('form')">更新密码</el-button>
        <el-button @click="resetForm('form')">重置</el-button>
      </el-form-item>
    </el-form>
  </template>
  
  <script>
  import { updatePassword } from '@/api/user'
  
  export default {
    data() {
      return {
        form: {
          oldPassword: '',
          password: '',
          confirmPassword: ''
        },
        rules: {
          oldPassword: [
            { required: true, message: '请输入旧密码', trigger: 'blur' }
          ],
          password: [
            { required: true, message: '请输入新密码', trigger: 'blur' },
            { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
          ],
          confirmPassword: [
            { required: true, message: '请确认新密码', trigger: 'blur' },
            { validator: (rule, value, callback) => {
              if (value !== this.form.password) {
                callback(new Error('两次输入的新密码不一致'))
              } else {
                callback()
              }
            }, trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      async submitForm(formName) {
        this.$refs[formName].validate(async (valid) => {
          if (valid) {
            try {
              await updatePassword(this.form)
              this.$message.success('密码更新成功')
              this.resetForm(formName)
              this.$store.dispatch('logout')
              this.$router.push('/login')
            } catch (error) {
              console.error('密码更新失败:', error)
              this.$message.error('密码更新失败')
            }
          }
        })
      },
      resetForm(formName) {
        this.$refs[formName].resetFields()
      }
    }
  }
  </script>